package com.gitee.dufafei.spark.connector.redis

import com.gitee.dufafei.spark.pattern.{Borrow, Logging}
import redis.clients.jedis.{Jedis, JedisPool, JedisPoolConfig}

/**
 * <dependency>
 * <groupId>redis.clients</groupId>
 * <artifactId>jedis</artifactId>
 * <version>${jedis.version}</version>
 * </dependency>
 */
class RedisPool(func: () => JedisPool) extends Borrow with Serializable {

  lazy val pool: JedisPool = func()

  def usingConnect[A](execute: Jedis => A): A = using(pool.getResource)(execute)
}

object RedisPool extends Logging {

  def apply(
             host: String,
             port: Int,
             password: String,
             timeout: Int = 1000 * 2): RedisPool = {
    val func = () => {
      val config = new JedisPoolConfig
      val pool = new JedisPool(config, host, port, timeout, password)
      sys.addShutdownHook {
        info(s"Execute hook thread: $name")
        pool.destroy()
      }
      pool
    }
    new RedisPool(func)
  }
}